<?php
namespace app\api\controller\wanlshop;

use addons\wanlshop\library\WanlSdk\Common;
use app\admin\model\wanlshop\Arrivalaudit;
use app\api\model\wanlshop\UserArrivalOrder;
use app\common\controller\Api;
use app\common\library\SfdPay;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 * 入驻
 */
class Arrival extends Api
{
    /**
     * Arrival模型对象
     * @var \app\admin\model\wanlshop\Arrival
     */
    protected $model = null;
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Arrival;
    }

    /**
     *获取入驻信息列表
     * @return void
     ** @throws DbException|\think\Exception
     */
    public function getArrivalList(){
       $info = cjsj($this->auth->id);
        $Language = input('Language');
        $query =  $this->model->where(['status'=>1]);
        if($info['is_shop'] > 0 || $info['is_cj'] > 0){
            $query = $query->whereNotIn('id', '1,2');
        }
        $arrivalAuditModel = new Arrivalaudit();
        $data =$query->paginate()->toArray();
        foreach ($data['data'] as $k=>&$v){
            $userAudit = $arrivalAuditModel->where(['user_id'=>$this->auth->id,'arrival_id'=>$v['id']])->value('status');
            if(!isset($userAudit)){
                $v['user_status'] = -1;
            }else{
                $v['user_status'] =(int)$userAudit;
            }
            if($Language != 'zh-CN'){
                $v['title'] = language($Language,'arrival',$v['title']);
            }
        }
        $this->success('返回成功', $data);
    }


    /**
     *获取翻译或者车辆司机列表
     * @return void
     ** @throws DbException
     */
    public function getArrivalAuditList(){
        $model = new Arrivalaudit();
        $arrivalId = input('arrival_id');
        if(!$arrivalId){
            $arrivalId = 3;
        }
        $where = ['arrival_id'=>$arrivalId,'Arrivalaudit.status'=>1];
        $keywords = input('keyword');
        if($keywords){
            $where['Arrivalaudit.username|Arrivalaudit.phone'] = ['like',"%$keywords%"];
        }
        $type = input('type');
        if(isset($type) && $type !== ''){
            $where['Arrivalaudit.type'] = $type;
        }
        $data = $model->with(['user'])->where($where)->order('id desc')->paginate();
        $Language = input('Language','');
        foreach ($data as $row) {
            if($Language){
                if(containsChinese($row->content) && $Language == 'zh-CN'){
                    continue;
                }
                $row->content = language($Language,'arrival',$row->content);
            }
            $row->getRelation('user')->visible(['id', 'avatar','username']);
        }
        $this->success('返回成功', $data);
    }

    /**
     *获取入驻详情
     * @return void
     ** @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function arrivalInfo(){
        $ids = input('id');
        $info = $this->model->where(['id'=>$ids,'status'=>1])->find();
        if(!$info){
            $this->error('数据不存在获已下架');
        }
        $arrivalAuditModel = new Arrivalaudit();
        $info['required_data_arr'] = explode(',', $info['required_data']);
        $where = ['user_id'=>$this->auth->id,'arrival_id'=>$ids];
        $info['arrival_info'] =  $arrivalAuditModel->where($where)->find();
        $this->success('返回成功', $info);
    }

    /**
     *提交申请
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function addData(){
        $ids = input('id');
        if(!$ids){
            $this->error('缺少参数');
        }
        if($ids == 1 || $ids == 2){
            $info = cjsj($this->auth->id);
            if($info['is_shop'] > 0 || $info['is_cj'] > 0){
                $this->error('请勿重复申请');
            }
        }
        $type = input('type');
        if(!in_array($type, [1,2])){
            $this->error('type类型错误');
        }
        $params = input('post.');
        $imageArr = $params['images'];
        if(!count($imageArr)){
            $this->error('请上传资料');
        }
        $info = $this->model->where(['id'=>$ids,'status'=>1])->find();
        if(!$info){
            $this->error('数据不存在获已下架');
        }
        $avatar = input('avatar','');
        if($info['id'] == 3 && !$avatar){
            $this->error('请上传头像');
        }
        if($info['id'] == 4 && !$avatar){
            $this->error('请上传车辆图片');
        }
        if($info['id'] != 3 && $info['id'] != 4 ){
            $typeArr = explode(',', $info['nationality_data']);
            if(!in_array($type, $typeArr)){
                $this->error('认证类型不合规');
            }
        }

        $arrivalAuditModel = new Arrivalaudit();
        $arrivalInfo = $arrivalAuditModel->where(['user_id'=>$this->auth->id,'arrival_id'=>$ids])->find();
        if($arrivalInfo){
            if($arrivalInfo['status'] == 0){
                $this->error('请勿重复提交');
            }
            if($arrivalInfo['status'] == 1){
                //修改
                $arrivalAuditModel = $arrivalInfo;
            }
        }
        $phone = input('phone');
        $email = input('email');
        $publicAccount = input('public_account');
        $content = input('content');
        $wx = input('wx');
        Db::startTrans();
        try {
            $arrivalAuditModel->is_china = input('is_china',1);
            $arrivalAuditModel->user_id     = $this->auth->id;
            $arrivalAuditModel->type        = $type;
            $arrivalAuditModel->arrival_id  = $info['id'];
            $arrivalAuditModel->smallimages = implode(',', $imageArr);
            $arrivalAuditModel->username    = input('username');
            $arrivalAuditModel->card_number = input('card_number');
            $arrivalAuditModel->bank_name   = input('bank_name');

            if($publicAccount){
                $arrivalAuditModel->public_account = $publicAccount;
            }
            if($content){
                $arrivalAuditModel->content = $content;
            }
            if($phone){
                $arrivalAuditModel->phone = $phone;
            }
            if($email){
                $arrivalAuditModel->email = $email;
            }
            if($wx){
                $arrivalAuditModel->wx = $wx;
            }
            if($info['id'] == 3 || $info['id'] == 4){
                $arrivalAuditModel->status = 1;
                $arrivalAuditModel->avatar = $avatar;
            }
            $arrivalAuditModel->save();
            Db::commit();
        }catch (\Throwable $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success('申请成功');
    }


    /**
     *创建订单
     * @return void
     ** @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function orderAdd(){
        $config = get_addon_config('wanlshop');
        $orderModel = new UserArrivalOrder();
        $arrivalId = input('post.id');
        if(!$arrivalId){
            $this->error('缺少参数');
        }
        $arrivalInfo = $this->model->where(['id'=>$arrivalId,'status'=>1])->find();
        if(!$arrivalInfo){
            $this->error('数据不存在获已下架');
        }
        if($arrivalInfo['fee_switch'] == 0 || $arrivalInfo['money'] <= 0){
            $this->error('此服务无需支付');
        }
        $orderModel->user_id = $this->auth->id;
        $orderModel->order_no = $this->auth->id;
        $orderModel->arrival_id = $arrivalId;
        $orderModel->money = $arrivalInfo['money'];
        $r = $orderModel->save();
        if($r){
            $redis = Common::redis();
            $redis->set('orderInfo-'.$orderModel->id, json_encode(input('post.')));
            $sfdClass = new SfdPay();
            $params['return_url'] =  $config['h5']['domain'].'/web/pages/page/success?type=arrival';
            $params['notify_url'] = $config['h5']['domain'].'/api/wanlshop/callback/notify/type/sfd';
            $params['party_order_number'] = $orderModel->order_no;
            $params['total_amount'] = $arrivalInfo['money'];
            $params['client_ip'] = get_client_ip();
            $params['subject'] = $arrivalInfo['title'];
            $params['payment'] = 1;
            $params['timestamp'] = time();
            $params['business_code'] = config('site.sfd_business_code');
            $params['mch_num'] = config('site.sfd_mch_num');
            $params['sign']  = $sfdClass->sign($params);
            $res =  $sfdClass->curlPost(config('site.sfd_url').'/pay_gate/app_pay', $params);
            $this->success('',json_decode($res,true));
        }
        $this->error('订单创建失败');
    }
}
